package tk.winshu.shortestpath.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tk.winshu.shortestpath.model.Node;
import tk.winshu.shortestpath.model.NodeData;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jason Krebs
 * @date 2015年2月7日
 */
public class ImportUtil {

    private static final Logger log = LoggerFactory.getLogger(ImportUtil.class.getName());

    static final String NODES_TAG = "nodes";
    static final String LINES_TAG = "lines";
    static final String SOURCE_TAG = "source";
    static final String TARGET_TAG = "target";

    static final String START_TAG = "start";
    static final String END_TAG = "end";

    static final String INDEX_TAG = "index";
    static final String LOCATION_TAG = "location";

    /**
     * 导入Node信息
     */
    public static NodeData importFrom(String path) {
        NodeData data = new NodeData();

        String source = FileUtil.loadFrom(path);
        if (source == null || source.isEmpty()) {
            return data;
        }

        JSONObject object = JSONObject.parseObject(source);

        JSONArray nodeArray = object.getJSONArray(NODES_TAG);
        Map<Integer, Node> nodesMap = parseNode(nodeArray);

        JSONArray lineArray = object.getJSONArray(LINES_TAG);
        data.setNodes(parseLine(lineArray, nodesMap));

        data.setStartIndex(object.getIntValue(SOURCE_TAG));
        data.setEndIndex(object.getIntValue(TARGET_TAG));

        return data;
    }

    private static List<Node> parseLine(JSONArray lineArray, Map<Integer, Node> nodesMap) {
        List<Node> nodes = new ArrayList<>();
        if (lineArray == null) {
            return nodes;
        }
        for (int i = 0; i < lineArray.size(); i++) {
            JSONObject line = lineArray.getJSONObject(i);

            int start = line.getIntValue(START_TAG);
            int end = line.getIntValue(END_TAG);

            Node startNode = nodesMap.get(start);
            Node endNode = nodesMap.get(end);

            if (startNode == null || endNode == null) {
                continue;
            }
            startNode.relationTo(endNode);
        }
        nodes.addAll(nodesMap.values());

        return nodes;
    }

    private static Map<Integer, Node> parseNode(JSONArray nodeArray) {
        Map<Integer, Node> nodes = new HashMap<>();
        for (int i = 0; i < nodeArray.size(); i++) {
            JSONObject nodeObject = nodeArray.getJSONObject(i);
            Node node = JSONObject.parseObject(nodeObject.toJSONString(), Node.class);
            if (node != null) {
                nodes.put(node.getIndex(), node);
            }
        }
        log.info(String.format("节点数量：%d", nodes.size()));
        return nodes;
    }
}
